package org.cy.algorithm.chapter_05;

import java.util.HashMap;
import java.util.Map;

public class Random_5_1_3 {

    // 条件使用 p概率返回1，1-p概率返回0的 函数，创建一个等概率返回0,1的函数
    public int basicRandom() {
        // 基本思路，random 两次，如果两次结果一样，重新random
        // 因为 两次ran的结果不一样的概率是  2 * p (1-p)。这个是等概率的。
        Random01 random01 = new Random01(0.2);
        int a = random01.random();
        int b = random01.random();
        if (a == b) {
            return basicRandom();
        }
        return a;
    }

    public static class Random01 {
        private final double p;

        public Random01(double p) {
            this.p = p;
        }

        // p概率输出1， 1-p概率输出0
        public int random() {
            return Math.random() < p ? 1 : 0;
        }
    }

    public static void main(String[] args) {
//        testRandom01();
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int i = 0; i < 1000000; i++) {
            int random = new Random_5_1_3().basicRandom();
            countMap.put(random, countMap.getOrDefault(random, 0) + 1);
        }
        countMap.forEach((k, v) -> System.out.println(k + ": " + v));
    }

    private static void testRandom01() {
        Random01 random01 = new Random01(0.3);
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int i = 0; i < 1000000; i++) {
            int random = random01.random();
            countMap.put(random, countMap.getOrDefault(random, 0) + 1);
        }

        countMap.forEach((k, v) -> System.out.println(k + ": " + v));
    }
}
